package com.escape.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.escape.auth.application.convert.AuthUserDTOConverter;
import com.escape.auth.application.dto.AuthUserDTO;
import com.escape.auth.common.entity.Result;
import com.escape.auth.domain.entity.AuthUserBO;
import com.escape.auth.domain.service.AuthUserDomainService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author: escape_zebra
 * @CreateTime: 2025-01-07  20:42
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户注册
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto: {}", JSON.toJSONString(authUserDto));
            }
            checkArgument(authUserDto);
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.register(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error", e.getMessage(), e);
            return Result.fail("注册用户失败!");
        }
    }

    /**
     * 更新用户信息
     */
    @RequestMapping("update")
    public Result<Boolean> update (@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto: {}", JSON.toJSONString(authUserDto));
            }
            checkArgument(authUserDto);

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.update.error", e.getMessage(), e);
            return Result.fail("更新用户失败!");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkNotNull(authUserDto.getId(),"id 不能为空!");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(this.authUserDomainService.delete(authUserBO));
        } catch (Exception e) {
            log.error("UserController.delete.error", e.getMessage(), e);
            return Result.fail("删除用户失败!");
        }
    }

    /**
     * 用户启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto: {}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkNotNull(authUserDto.getId(), "id 不能为空!");
            Preconditions.checkNotNull(authUserDto.getStatus(), "状态不能为空!");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(this.authUserDomainService.changeStatus(authUserBO));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error", e.getMessage(), e);
            return Result.fail("修改用户状态失败!");
        }
    }

    /**
     * 修改 + 新增 dto 校验
     */
    private void checkArgument(AuthUserDTO authUserDto){
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()), "账户不能为空!");
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getEmail()), "邮箱不能为空!");
    }

    /**
     * 验证码登录
     */
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode){
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(validCode), "验证码不能为空!");
            SaTokenInfo tokenInfo = this.authUserDomainService.doLogin(validCode);
            return Result.ok(tokenInfo);
        } catch (Exception e) {
            log.error("UserController.doLogin.error", e.getMessage(), e);
            return Result.fail("用户登录失败!");
        }
    }

    // 测试登录
//    @RequestMapping("doLogin")
//    public SaResult doLogin(String username, String password){
//        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
//        if("jichi".equals(username) && "123123".equals(password)) {
//            StpUtil.login("jichi");
//            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//            return SaResult.data(tokenInfo);
//        }
//        return SaResult.error("登录失败!");
//    }

    // 查询登录状态
    @RequestMapping("isLogin")
    public String isLogin(){
        return "当前会话是否登录:" + StpUtil.isLogin();
    }

    @RequestMapping("logout")
    public String logout(){
        StpUtil.logout(10001);
        return "清楚成功";
    }

}
